package com.androturka.billintur.cyberpark;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class MenuDownloader {

	final String urlStr = "http://www.depremgunlugu.com/yemekhane/menu.xml";

	
	final private String gunlukStr 		= "gunluk";
	final private String tarihStr 			= "tarih";
	final private String corbaStr 			= "corba";
	final private String anayemek1Str 		= "anayemek1";
	final private String anayemek2Str 		= "anayemek2";
	final private String vejeteryanStr 	= "vejeteryan";
	final private String pilavStr 			= "pilav";
	final private String makarnaborekStr 	= "makarnaborek";
	final private String zeytinyagliStr 	= "zeytinyagli";
	final private String tatli1Str 		= "tatli1";
	final private String tatli2Str 		= "tatli2";
	final private String meyveStr 			= "meyve";
	final private String salataStr 		= "salata";

	String tarih 		= null;
	String corba 		= null;
	String anayemek1 	= null;
	String vejeteryan 	= null;
	String anayemek2 	= null;
	String pilav 		= null;
	String makarnaborek = null;
	String zeytinyagli 	= null;
	String tatli1 		= null;
	String tatli2 		= null;
	String meyve 		= null;
	String salata 		= null;

	
	NodeList nodeListMenu = null; 
	private YemekhaneDB DB;
	Context mContext;

	public MenuDownloader(Context mContext){
		this.DB = YemekhaneDB.getInstance(mContext);
		this.mContext = mContext;
	}
	
	public void download(){
		
		try {
			
	     	DailyMenu todaymenu = DB.getMenu(Common.getDateStr());
	     	int dayOfWeek = Common.getDayOfWeek(new Date());
	     	Log.d(Common.TAG, "dayOfWeek : " + dayOfWeek );
	     	
	     	if ( todaymenu == null )
	     		Log.d(Common.TAG, "today's menu is null");
	     	else
	     		Log.d(Common.TAG, "today's menu found");
	     	
			if ( ( ( todaymenu == null ) /*&& 
			       ( dayOfWeek != 7 ) &&
			       ( dayOfWeek != 1 ) */) || 
			     ( DB.getMenuCount() == 0 ) ){
				
				Log.d(Common.TAG, "Get New Menu");
				
				URL url = new URL(urlStr);
	
				ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo netInfo = cm.getActiveNetworkInfo();
				
				
				if ( netInfo != null && netInfo.isConnectedOrConnecting()) {
				
					
					DocumentBuilderFactory dFactory=DocumentBuilderFactory.newInstance();
					DocumentBuilder dBuilder=dFactory.newDocumentBuilder();
					Document document=dBuilder.parse(new InputSource(url.openStream()));
					
					
					document.getDocumentElement().normalize();
					nodeListMenu=document.getElementsByTagName(gunlukStr);
	
					Log.d(Common.TAG, "toplam " + nodeListMenu.getLength());
		
					
					int previousMonth = 0;
					int currrentMonth = 0;
					
					for (int i = 0; i < nodeListMenu.getLength(); i++) {
		
						String tarih = null;
						String corba = null;
						String anayemek1 = null;
						String vejeteryan = null;
						String anayemek2 = null;
						String pilav = null;
						String makarnaborek = null;
						String zeytinyagli = null;
						String tatli1 = null;
						String tatli2 = null;
						String meyve = null;
						String salata = null;
						
						
						Node node=nodeListMenu.item(i);
						Element elementMain=(Element) node;
						
						tarih 			= getElementValue(elementMain,tarihStr);
						corba 			= getElementValue(elementMain,corbaStr);
						anayemek1 		= getElementValue(elementMain,anayemek1Str);
						anayemek2 		= getElementValue(elementMain,anayemek2Str);
						vejeteryan 		= getElementValue(elementMain,vejeteryanStr);
						pilav 			= getElementValue(elementMain,pilavStr);
						makarnaborek 	= getElementValue(elementMain,makarnaborekStr);
						zeytinyagli 	= getElementValue(elementMain,zeytinyagliStr);
						tatli1 			= getElementValue(elementMain,tatli1Str);
						tatli2 			= getElementValue(elementMain,tatli2Str);
						meyve 			= getElementValue(elementMain,meyveStr);
						salata 			= getElementValue(elementMain,salataStr);
						
						//Log.d(Common.TAG, "Get Menu Count : " + i + "  date : " + tarih);
						
						if ( i == 0 )
							previousMonth = Integer.parseInt(tarih.substring(3, 5));
							
						currrentMonth = Integer.parseInt(tarih.substring(3, 5));
						
						//Log.d(Common.TAG, tarih + " " +previousMonth + " " + currrentMonth);
						if (( i > 7 ) && ( currrentMonth != previousMonth )) {
							Log.d(Common.TAG, "Next Month");
						}
						else {
						
							DailyMenu menu = new DailyMenu();
							
							menu.setTarih(tarih);
							menu.setCorba(corba);
							menu.setAnayemek1(anayemek1);
							menu.setAnayemek2(anayemek2);
							menu.setVejeteryan(vejeteryan);
							menu.setPilav(pilav);
							menu.setMakarnaborek(makarnaborek);
							menu.setZeytinyagli(zeytinyagli);
							menu.setTatli1(tatli1);
							menu.setTatli2(tatli2);
							menu.setMeyve(meyve);
							menu.setSalata(salata);
							
							
							if ( i == 0 )
								DB.deleteAllMenus();
							
							DB.insertMenu(menu);
							
							//Log.d("menu",menu.toString());
						}
						
						previousMonth = currrentMonth;
					}
				}
			}	
				
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	private String getElementValue(Element elementMain, String elementname) {
		
		String value = null;
		
		NodeList nodeList=elementMain.getElementsByTagName(elementname);
		Element element=(Element) nodeList.item(0);
		if (( element != null ) && 
			( element.getChildNodes() != null ) && 
			( element.getChildNodes().item(0) != null ))
		{
			value = element.getChildNodes().item(0).getNodeValue();
		}	

		return value;
	}

	public void setAlarm() {
    	Boolean workAtBackGround = DB.getWorkAtBackGround();
    	
    	if ( workAtBackGround ) {
    		Log.d(Common.TAG, "Background Notification is Active");
    		
        	String notificationTime = DB.getNotificationTime();
	    	Log.d(Common.TAG,"notification time : " + notificationTime);
	    	int notificationTimeInt = Integer.parseInt(notificationTime);
	    	int hour = notificationTimeInt / 100;
	    	int min = notificationTimeInt % 100;
	    	
	    	Log.d(Common.TAG, hour + " : " + min );
	    	
			// get a Calendar object with current time
			Calendar cal = Calendar.getInstance();
			// add 5 minutes to the calendar object
			//cal.add(Calendar.SECOND, 10);
	
		    cal.setTimeInMillis(System.currentTimeMillis());
		    cal.set(Calendar.HOUR_OF_DAY, hour);
		    cal.set(Calendar.MINUTE, min);
		    cal.set(Calendar.SECOND, 0);
		    cal.set(Calendar.MILLISECOND, 0);
	
		    //check if we want to wake up tomorrow
		    if (System.currentTimeMillis() > cal.getTimeInMillis()){
		        cal.setTimeInMillis(cal.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
		    }
		    
			Intent intent = new Intent(mContext, AlarmReceiver.class);
			intent.putExtra("alarm_message", "notify");
			PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			 
			// Get the AlarmManager service
			AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);		
    	}
    	else
    		Log.d(Common.TAG, "Background Notification is Disabled");
	}
	
	public void cancelAlarm() {

		Intent intent = new Intent(mContext, AlarmReceiver.class);
		intent.putExtra("alarm_message", "notify");
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		 
		// Get the AlarmManager service
		AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		am.cancel(sender);		
	}
	
}
